package Controllers;

import Connection.User;
import Connection.WorldListLoader;
import Connection.WebWorldListLoader;
import Entities.World;
import SwingComponents.IDButton;
import SwingComponents.SelectWorldPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class SelectWorldController implements ActionListener {

    private PrincipalController principalController;
    private WorldListLoader worldListLoader;
    private SelectWorldPanel selectWorldPanel;
    private User user;

    public SelectWorldController(PrincipalController principalController, User user) {
        this.principalController = principalController;
        worldListLoader = new WebWorldListLoader(principalController.getApplication());
        initSelectWorldPanel();
        this.user = user;
    }

    private void initSelectWorldPanel() {
        selectWorldPanel = new SelectWorldPanel(this, worldListLoader.loadWorldList());
        selectWorldPanel.setVisible(true);
        principalController.getApplication().add(selectWorldPanel);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Back")) {
            selectWorldPanel.setVisible(false);
            principalController.getApplication().remove(selectWorldPanel);
            principalController.getPrincipalPanel().setVisible(true);
        } else {
            IDButton boton = (IDButton) e.getSource();
            Integer number = boton.getId();
            World world = selectWorldPanel.getWorldList().get(number);
            selectWorldPanel.setVisible(false);
            SelectPhaseController selectPhaseController = new SelectPhaseController(principalController, world.getId(), user);
            selectPhaseController.execute();
        }
    }

    public PrincipalController getPrincipalController() {
        return principalController;
    }
}
